package api

import (
	"context"
	"github.com/gin-gonic/gin"
	"kuangstudy-mall/apis/order-web/microservices"
	context2 "kuangstudy-mall/apis/order-web/models/context"
	"kuangstudy-mall/apis/order-web/proto"
	"kuangstudy-mall/apis/order-web/validation"
	"strconv"
)

type OrderApi struct {
	BaseApi
}

/*
*
查询用户订单
*/
func (api *OrderApi) FindCartListByUserId(ctx *gin.Context) {
	orderContext := context2.OrderContext{}
	err := ctx.ShouldBindJSON(&orderContext)
	if err != nil {
		api.FailCodeMsgAny(603, validation.GetErrors(err, orderContext), ctx)
		return
	}
	userId := ctx.GetUint64("userId")
	orderFilterRequest := proto.OrderFilterRequest{
		UserId:   userId,
		PageNo:   orderContext.PageNo,
		PageSize: orderContext.PageSize,
	}
	orderListResponse, err := microservices.GetNacosOrderClient().FindGoodsOrderList(context.Background(), &orderFilterRequest)
	if err != nil {
		api.handlerGrpcError(err, ctx)
		return
	}
	api.OK(orderListResponse, ctx)
}

/*
*
查询订单明细
*/
func (api *OrderApi) FindGoodsOrderDetail(ctx *gin.Context) {
	orderIdStr, _ := ctx.GetQuery("orderId")
	userId := ctx.GetUint64("userId")
	orderId, _ := strconv.ParseUint(orderIdStr, 10, 64)
	orderRequest := proto.OrderRequest{
		Id:     orderId,
		UserId: userId,
	}
	orderInfoDetailResponse, err := microservices.GetNacosOrderClient().FindGoodsOrderDetail(context.Background(), &orderRequest)
	if err != nil {
		api.handlerGrpcError(err, ctx)
		return
	}
	api.OK(orderInfoDetailResponse, ctx)
}

/*
*
创建订单
*/
func (api *OrderApi) CreateGoodsOrder(ctx *gin.Context) {
	orderCreateContext := context2.OrderCreateContext{}
	err := ctx.ShouldBindJSON(&orderCreateContext)
	if err != nil {
		api.FailCodeMsgAny(603, validation.GetErrors(err, orderCreateContext), ctx)
		return
	}
	userId := ctx.GetUint64("userId")
	orderRequest := proto.OrderRequest{
		UserId:   userId,
		Address:  orderCreateContext.Address,
		Username: orderCreateContext.Username,
		Mobile:   orderCreateContext.Mobile,
		Post:     orderCreateContext.Post,
	}

	shopcartItemsResponse, err := microservices.GetNacosOrderClient().CreateGoodsOrder(context.Background(), &orderRequest)
	if err != nil {
		api.handlerGrpcError(err, ctx)
		return
	}
	api.OK(shopcartItemsResponse, ctx)
}

/*
*修改订单状态
 */
func (api *OrderApi) UpdateGoodsOrderStatus(ctx *gin.Context) {
	orderStatusContext := context2.OrderStatusContext{}
	err := ctx.ShouldBindJSON(&orderStatusContext)
	if err != nil {
		api.FailCodeMsgAny(603, validation.GetErrors(err, orderStatusContext), ctx)
		return
	}
	srderStatus := proto.OrderStatus{
		OrderStatus: orderStatusContext.OrderStatus,
		OrderNo:     orderStatusContext.OrderNo,
	}
	shopcartItemsResponse, err := microservices.GetNacosOrderClient().UpdateGoodsOrderStatus(context.Background(), &srderStatus)
	if err != nil {
		api.handlerGrpcError(err, ctx)
		return
	}
	api.OK(shopcartItemsResponse, ctx)
}
